<template>
    <div>
      <h3>登录页面</h3>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>

  </el-form>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
    export default {
      data() {
        var validaUser = (rule, value, callback) => {
          if (!value) {
            return callback(new Error('用户名不能为空'));
          }
          const userRules=/^[a-zA-Z][a-zA-Z0-9]{4,15}$/
          if(userRules.test(value)){
              axios.get('http://127.0.0.1:8000/user/checkname/'+value+'/')
              .then(resp=>{
                  console.log(resp);
                  return callback()
              })
              .catch(err=>{
                  console.log(err);
              })
              
          }else{
              return callback(new Error('用户名格式不正确'));
          }
        };
        var validatePass = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'));
          } 
          const passRules=/^[a-zA-Z][a-zA-Z0-9]{4,15}$/
          if(passRules.test(value)){
              return callback()
          }else{
              return callback(new Error('密码格式不正确'));
          }
        };

  
        return {
          ruleForm: {
            username:'',
            password: '',

          },
          rules: {
              username: [
              { validator: validaUser, trigger: 'blur' }
            ],
            password: [
              { validator: validatePass, trigger: 'blur' }
            ],

          }
        };
      },
      mounted(){

      },
      methods: {

        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              axios.post('http://127.0.0.1:8000/user/login/',this.ruleForm)
              .then(resp=>{
                  console.log(resp);
                  alert('登录成功')
                  this.$router.push('/index')
              })
              .catch(err=>{
                  console.log(err);
              })
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        resetForm(formName) {
          this.$refs[formName].resetFields();
        }
      }
    }
  </script>
  
  <style>
  
  </style>